<template>
  <div id="excel-demo">
    <!-- 输入框用于输入文档的网络地址 -->
    <el-input
      placeholder="请输入Excel文档网络地址"
      v-model="excelUrl"
      style="width: 300px; margin-bottom: 20px;"
    />
    <el-button type="primary" @click="previewExcel" style="margin-bottom: 20px;">
      预览
    </el-button>

    <el-upload
      :limit="1"
      :file-list="fileList"
      accept=".xlsx, .xls"
      :beforeUpload="beforeUpload"
      action=""
      style="margin-bottom: 20px;"
    >
      <el-button size="small" type="warning">上传文件</el-button>
    </el-upload>

    <vue-office-excel
      v-if="src"
      :src="src"
      :options="options"
      style="height: 100vh;"
      @rendered="renderedHandler"
      @error="errorHandler"
    />
  </div>
</template>

<script>
// 引入 VueOfficeExcel 组件
import VueOfficeExcel from '@vue-office/excel';
// 引入相关样式
import '@vue-office/excel/lib/index.css';

export default {
  name: "VueOfficeExcelDemo",
  components: {
    VueOfficeExcel
  },
  data() {
    return {
      excelUrl: '', // Excel文档网络地址输入框
      src: '', // 存储渲染的文档源
      fileList: [], // 上传文件列表
      options: {
        xls: false,
        minColLength: 0,
        minRowLength: 0,
        widthOffset: 10,
        heightOffset: 10,
        beforeTransformData: (workbookData) => { return workbookData }, // 处理读取到的excel数据
        transformData: (workbookData) => { return workbookData },
      }
    };
  },
  methods: {
    // 上传文件前的处理
    beforeUpload(file) {
      let reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onload = (loadEvent) => {
        let arrayBuffer = loadEvent.target.result;
        // 将上传的文件内容设置为src
        this.src = arrayBuffer;
      };
      return false; // 阻止自动上传
    },
    // 预览输入的Excel文档
    previewExcel() {
      if (this.excelUrl) {
        this.src = this.excelUrl; // 更新src为输入的网址
      } else {
        this.$message.warning("请输入有效的文档地址或上传文件进行预览。");
      }
    },
    renderedHandler() {
      console.log("渲染完成");
    },
    errorHandler() {
      console.log("渲染失败");
    }
  }
};
</script>

<style scoped>
#excel-demo {
  padding: 20px;
}
</style>
